package com.stx.jeepay.merchant.controller;

import com.alibaba.fastjson.JSONObject;
import com.stx.jeepay.core.entity.MchAppEntity;
import com.stx.jeepay.core.service.MchAppService;
import com.stx.jeepay.core.utils.JeepayKit;
import com.stx.jeepay.merchant.websocket.server.WsPayOrderServer;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@Api(tags = "支付测试")
@RestController
@RequestMapping("/api/anon/paytestNotify")
public class PaytestNotifyController extends CommonCtrl {

    @Autowired
    private MchAppService mchAppService;

    @ApiOperation("支付回调信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "appId", value = "应用ID", required = true),
            @ApiImplicitParam(name = "mchNo", value = "商户号", required = true),
            @ApiImplicitParam(name = "sign", value = "签名值", required = true)
    })
    @RequestMapping("/payOrder")
    public void payOrderNotify() throws IOException {
        JSONObject paramJSON = getReqParamJSON();

        String mchNo = paramJSON.getString("mchNo");
        String appId = paramJSON.getString("appId");
        String sign = paramJSON.getString("sign");
        MchAppEntity mchApp = mchAppService.getById(appId);
        if (mchApp == null || !mchApp.getMchNo().equals(mchNo)) {
            response.getWriter().print("app is not exists");
            return;
        }

        paramJSON.remove("sign");
        if (!JeepayKit.getSign(paramJSON, mchApp.getAppSecret()).equalsIgnoreCase(sign)) {
            response.getWriter().print("sign fail");
            return;
        }

        JSONObject msg = new JSONObject();
        msg.put("state", paramJSON.getIntValue("state"));
        msg.put("errCode", paramJSON.getString("errCode"));
        msg.put("errMsg", paramJSON.getString("errMsg"));

        //推送到前端
        WsPayOrderServer.sendMsgByOrderId(paramJSON.getString("payOrderId"), msg.toJSONString());

        response.getWriter().print("SUCCESS");
    }
}
